﻿using ModelLibrary;
using ModelLibrary.Image;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Reflection;
using System.Windows.Forms;

namespace IMSTools
{
    public delegate void QuitHandle(object form);
    public partial class FmReceipt : Form
    {
        #region 属性定义


        public event QuitHandle formQuit;
        /// <summary>
        /// plMain中，鼠标光标样式
        /// </summary>
        public CtrTypeStyle MouseCursorDefaulted = CtrTypeStyle.None;
        /// <summary>
        /// 用于拖控件定位
        /// </summary>
        private int X = 1;
        /// <summary>
        /// 用于拖控件定位
        /// </summary>
        private int Y = 1;
        /// <summary>
        /// 用于拖抬头高度
        /// </summary>
        private int plMainSizeY = 0;
        /// <summary>
        /// 用于判断抬头是否处于调整大小中
        /// </summary>
        private bool isSizeChanging = false;
        /// <summary>
        /// 用于判断控件是否处于调整大小中
        /// </summary>
        private bool isControlSizeChanging = false;
        /// <summary>
        /// 修改尺寸时的光标方向
        /// </summary>
        private SizeChangeCursorDirection sizeChangeCursorDirection = SizeChangeCursorDirection.None;
        /// <summary>
        /// 修改控件尺寸时的鼠标位置
        /// </summary>
        Point ControlSizeChangeMousePosition = new Point(0, 0);
        /// <summary>
        /// 按下控件的鼠标位置
        /// </summary>
        Point ControlDownMousePosition = new Point(0, 0);
        /// <summary>
        ///显示拖动效果的矩形
        /// </summary>
        Rectangle rect = Rectangle.Empty;
        /// <summary>
        /// 用于设置控件属性
        /// </summary>
        private Control controlAttributes = new Control();
        #endregion

        public FmReceipt()
        {
            InitializeComponent();
            this.FormClosed += Form_Closed;
        }

        private void PlMain_MouseHover(object sender, EventArgs e)
        {
            Point point = this.plMain.PointToClient(MousePosition);
            this.toolStripStatusLabel1.Text = "横坐标：" + point.X.ToString();
            this.toolStripStatusLabel2.Text = "纵坐标：" + point.Y.ToString(); ;
            this.toolStripStatusLabel3.Text = "Width：";
            this.toolStripStatusLabel4.Text = "Hight：";
        }

        private void FmReceipt_Load(object sender, EventArgs e)
        {
            this.plMain.MouseClick += PlMain_MouseClick;
            this.plMain.MouseMove += PlMain_MouseMove;
            this.plMain.MouseDown += PlMain_MouseDown;
            this.plMain.MouseUp += PlMain_MouseUp;
            this.plMain.AutoSizeMode = AutoSizeMode.GrowOnly;
        }

        private void PlMain_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isSizeChanging = false;
            }
        }

        private void PlMain_MouseLeave(object sender, EventArgs e)
        {
            this.toolStripStatusLabel1.Text = "";
            this.toolStripStatusLabel2.Text = "";
            this.toolStripStatusLabel3.Text = "";
            this.toolStripStatusLabel4.Text = "";
        }

        private void PlMain_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && this.plMain.Cursor == Cursors.SizeNS)
            {
                isSizeChanging = true;
            }

        }

        private void PlMain_MouseMove(object sender, MouseEventArgs e)
        {
            Point point = this.plMain.PointToClient(MousePosition);
            this.toolStripStatusLabel1.Text = "横坐标：" + point.X.ToString();
            this.toolStripStatusLabel2.Text = "纵坐标：" + point.Y.ToString(); ;
            this.toolStripStatusLabel3.Text = "Width：";
            this.toolStripStatusLabel4.Text = "Hight：";

            #region 画虚拟框
            Graphics g = this.plMain.CreateGraphics();
            int x = 1 + point.X / 80;
            int y = 1 + point.Y / 30;
            if (x != X || y != Y)
            {
                g.Clear(this.plMain.BackColor);
                X = x;
                Y = y;
            }
            if (MouseCursorDefaulted != CtrTypeStyle.None)
            {
                Pen pen = new Pen(Brushes.Blue, 1);
                pen.DashStyle = DashStyle.Dash;
                //画位置
                g.DrawLine(pen, new Point((x - 1) * 80, (y - 1) * 30), new Point(x * 80, (y - 1) * 30));
                g.DrawLine(pen, new Point((x - 1) * 80, (y - 1) * 30), new Point((x - 1) * 80, y * 30));
                g.DrawLine(pen, new Point(x * 80, y * 30), new Point(x * 80, (y - 1) * 30));
                g.DrawLine(pen, new Point(x * 80, y * 30), new Point((x - 1) * 80, y * 30));

            }
            g.Dispose();
            #endregion

            if (MouseCursorDefaulted == CtrTypeStyle.None)
            {
                this.plMain.Cursor = e.Y > plMain.Size.Height - 15 ? Cursors.SizeNS : Cursors.Default;
                if (isSizeChanging)
                {
                    this.plMain.Height += e.Y - plMainSizeY;
                }

            }
            plMainSizeY = e.Y;
        }

        private void PlMain_MouseClick(object sender, MouseEventArgs e)
        {
            Graphics g = this.plMain.CreateGraphics();
            g.Clear(this.plMain.BackColor);
            g.Dispose();
            if (e.Button == MouseButtons.Left)
            {
                if (MouseCursorDefaulted != CtrTypeStyle.None)
                {
                    Point point = this.plMain.PointToClient(MousePosition);
                    int x = point.X / 80;
                    int y = point.Y / 30;
                    point.X = x * 80;
                    point.Y = y * 30;
                    #region //生成不同的控件
                    switch (MouseCursorDefaulted)
                    {
                        case CtrTypeStyle.None:
                            break;
                        case CtrTypeStyle.Button:
                            Button button = new Button();
                            button.Text = "新按钮";
                            button.Size = new Size(80, 26);
                            button.Location = new Point(point.X, point.Y);
                            button.Focus();
                            button.FlatStyle = FlatStyle.Flat;
                            button.ContextMenuStrip = contextMenuStrip控件;
                            button.KeyDown += Button_KeyDown;
                            button.MouseClick += Button_MouseClick;
                            button.MouseDown += Control_MouseDown;
                            button.MouseMove += Control_MouseMove;
                            button.MouseUp += Control_MouseUp;
                            plMain.Controls.Add(button);
                            break;
                        case CtrTypeStyle.ComboBox:
                            ComboBox comboBox = new ComboBox();
                            comboBox.Font = new Font(comboBox.Font.FontFamily, 12);
                            comboBox.Size = new Size(80, 30);
                            comboBox.FlatStyle = FlatStyle.Popup;
                            comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
                            comboBox.Location = new Point(point.X, point.Y);
                            comboBox.Focus();
                            comboBox.ContextMenuStrip = contextMenuStrip控件;
                            comboBox.KeyDown += ComboBox_KeyDown;
                            comboBox.MouseClick += ComboBox_MouseClick;
                            comboBox.MouseDown += Control_MouseDown;
                            comboBox.MouseMove += Control_MouseMove;
                            comboBox.MouseUp += Control_MouseUp;
                            plMain.Controls.Add(comboBox);
                            break;
                        case CtrTypeStyle.Label:
                            Label label = new Label();
                            label.Text = "文字Lable";
                            label.Size = new Size(80, 26);
                            label.Location = new Point(point.X, point.Y);
                            label.Anchor = AnchorStyles.Top & AnchorStyles.Bottom & AnchorStyles.Left & AnchorStyles.Right;
                            label.TextAlign = ContentAlignment.MiddleRight;
                            label.BorderStyle = BorderStyle.FixedSingle;
                            label.Focus();
                            label.ContextMenuStrip = contextMenuStrip控件;
                            label.PreviewKeyDown += Label_PreviewKeyDown;
                            label.MouseClick += Label_MouseClick;
                            label.MouseDown += Control_MouseDown;
                            label.MouseMove += Control_MouseMove;
                            label.MouseUp += Control_MouseUp;
                            plMain.Controls.Add(label);
                            break;
                        case CtrTypeStyle.TextBox:
                            TextBox textBox = new TextBox();
                            //textBox.AutoSize = false;
                            textBox.Font = new Font(textBox.Font.FontFamily, 12);
                            textBox.Size = new Size(80, 30);
                            textBox.BorderStyle = BorderStyle.FixedSingle;
                            textBox.Location = new Point(point.X, point.Y);
                            textBox.Focus();
                            textBox.ContextMenuStrip = contextMenuStrip控件;
                            textBox.KeyDown += TextBox_KeyDown;
                            textBox.MouseClick += TextBox_MouseClick;
                            textBox.MouseDown += Control_MouseDown;
                            textBox.MouseMove += Control_MouseMove;
                            textBox.MouseUp += Control_MouseUp;
                            plMain.Controls.Add(textBox);
                            break;
                        case CtrTypeStyle.CheckBox:
                            CheckBox checkBox = new CheckBox();
                            checkBox.Text = "多选框";
                            checkBox.Size = new Size(80, 30);
                            checkBox.Location = new Point(point.X, point.Y);
                            checkBox.Focus();
                            checkBox.ContextMenuStrip = contextMenuStrip控件;
                            checkBox.KeyDown += CheckBox_KeyDown;
                            checkBox.MouseClick += CheckBox_MouseClick;
                            checkBox.MouseDown += Control_MouseDown;
                            checkBox.MouseMove += Control_MouseMove;
                            checkBox.MouseUp += Control_MouseUp;
                            plMain.Controls.Add(checkBox);
                            break;
                    }
                    #endregion
                    this.plMain.Cursor = Cursors.Default;
                    MouseCursorDefaulted = CtrTypeStyle.None;
                }
            }
        }

        private void Form_Closed(object sender, EventArgs e)
        {
            formQuit(this.Text);
        }

        #region NewControls MouseEvent

        private void Control_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Clicks == 1 && e.Button == MouseButtons.Left)
            {
                rect = ((Control)sender).Bounds;
            }
            if (((Control)sender).Cursor != Cursors.Default)
            {
                isControlSizeChanging = true;
                ControlSizeChangeMousePosition = MousePosition;
            }
            ControlDownMousePosition = MousePosition;
        }

        private void Control_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && !isControlSizeChanging)
            {
                //重新设置rect的位置，跟随鼠标移动
                rect.Location = plMain.PointToClient(MousePosition);

                #region 画虚拟框
                Point point = this.plMain.PointToClient(MousePosition);
                Graphics g = this.plMain.CreateGraphics();
                int x = 1 + point.X / 80;
                int y = 1 + point.Y / 30;
                g.Clear(this.plMain.BackColor);
                if (x != X || y != Y)
                {
                    X = x;
                    Y = y;
                }

                Pen pen = new Pen(Brushes.Blue, 3);
                Pen pen_r = new Pen(Brushes.BlueViolet, 1);
                pen_r.DashStyle = DashStyle.Dash;
                Rectangle rectPlMain = new Rectangle(new Point(x * 80 - 80, y * 30 - 30), rect.Size);
                //plMain画框
                g.DrawRectangle(pen, rectPlMain);
                g.DrawRectangle(pen_r, rect);
                g.Dispose();
                #endregion

            }
            Control control = ((Control)sender);
            if (e.Button == MouseButtons.None || isControlSizeChanging)
            {
                if (!isControlSizeChanging)
                    ControlCursorChange(control);
                else
                    ControlSizeChange(control, MousePosition);
            }
        }

        private void Control_MouseUp(object sender, MouseEventArgs e)
        {
            //if (e.Button == MouseButtons.Left && Math.Abs(ControlDownMousePosition.X - MousePosition.X) < 2 && Math.Abs(ControlDownMousePosition.Y - MousePosition.Y) < 2)
            if (e.Button == MouseButtons.Left && ControlDownMousePosition != MousePosition)
            {
                if (((Control)sender).Cursor == Cursors.Default)
                {
                    Point point = this.plMain.PointToClient(MousePosition);
                    int x = point.X / 80;
                    int y = point.Y / 30;
                    point.X = x * 80;
                    point.Y = y * 30;

                    //移动control到放开鼠标的地方
                    ((Control)sender).Location = point;
                    this.Refresh();
                    reset();
                }
                else
                    isControlSizeChanging = false;
            }
            ControlDownMousePosition = new Point(0, 0);
        }

        private void reset()
        {
            rect = Rectangle.Empty;
        }
        /// <summary>
        /// 修改控件位置
        /// </summary>
        /// <param name="control"></param>
        private void ControlCursorChange(Control control)
        {
            int pad = 5;
            Point controlPoint = control.PointToClient(MousePosition);
            Rectangle rectangle = new Rectangle(pad, pad, control.Size.Width - pad * 2, control.Size.Height - pad * 2);
            #region 修改光标
            if (!rectangle.Contains(controlPoint))
            {
                if (controlPoint.X <= pad)
                {
                    if (controlPoint.Y <= pad)
                    {
                        control.Cursor = Cursors.SizeNWSE;
                        sizeChangeCursorDirection = SizeChangeCursorDirection.LeftTop;
                    }
                    else if (controlPoint.Y >= control.Size.Height - pad)
                    {
                        control.Cursor = Cursors.SizeNESW;
                        sizeChangeCursorDirection = SizeChangeCursorDirection.LeftBottom;
                    }
                    else
                    {
                        control.Cursor = Cursors.SizeWE;
                        sizeChangeCursorDirection = SizeChangeCursorDirection.Left;
                    }
                }
                else if (controlPoint.X >= control.Size.Width - pad)
                {
                    if (controlPoint.Y <= pad)
                    {
                        control.Cursor = Cursors.SizeNESW;
                        sizeChangeCursorDirection = SizeChangeCursorDirection.RightTop;
                    }
                    else if (controlPoint.Y >= control.Size.Height - pad)
                    {
                        control.Cursor = Cursors.SizeNWSE;
                        sizeChangeCursorDirection = SizeChangeCursorDirection.RightBottom;
                    }
                    else
                    {
                        control.Cursor = Cursors.SizeWE;
                        sizeChangeCursorDirection = SizeChangeCursorDirection.Right;
                    }
                }
                else
                {
                    if (controlPoint.Y <= pad)
                        sizeChangeCursorDirection = SizeChangeCursorDirection.Top;
                    else
                        sizeChangeCursorDirection = SizeChangeCursorDirection.Bottom;
                    control.Cursor = Cursors.SizeNS;
                }

            }
            else
            {
                control.Cursor = Cursors.Default;
            }
            #endregion
        }
        /// <summary>
        /// 修改控件尺寸
        /// </summary>
        /// <param name="control">被修改控件</param>
        /// <param name="point">鼠标位移坐标</param>
        private void ControlSizeChange(Control control, Point point)
        {
            int X = point.X - ControlSizeChangeMousePosition.X;
            int Y = point.Y - ControlSizeChangeMousePosition.Y;
            switch (Convert.ToInt32(sizeChangeCursorDirection))
            {
                case 0:
                    break;
                case 1:
                    control.Height -= Y;
                    control.Location = new Point(control.Location.X, control.Location.Y + Y);
                    break;
                case 2:
                    control.Width -= X;
                    control.Location = new Point(control.Location.X + X, control.Location.Y);
                    break;
                case 3:
                    control.Height -= Y;
                    control.Location = new Point(control.Location.X, control.Location.Y + Y);
                    control.Width -= X;
                    control.Location = new Point(control.Location.X + X, control.Location.Y);
                    break;
                case 4:
                    control.Width += X;
                    break;
                case 5:
                    control.Width += X;
                    control.Height -= Y;
                    control.Location = new Point(control.Location.X, control.Location.Y + Y);
                    break;
                case 8:
                    control.Height += Y;
                    break;
                case 10:
                    control.Height += Y;
                    control.Width -= X;
                    control.Location = new Point(control.Location.X + X, control.Location.Y);
                    break;
                case 12:
                    control.Height += Y;
                    control.Width += X;
                    break;
            }
            ControlSizeChangeMousePosition = point;
        }
        private void Control_MouseRightClick(Control control, MouseButtons mouseButton)
        {
            if (mouseButton == MouseButtons.Right)
            {
            }
        }

        private void Button_MouseClick(object sender, MouseEventArgs e)
        {
            Control_MouseRightClick((Control)sender, e.Button);
        }

        private void ComboBox_MouseClick(object sender, MouseEventArgs e)
        {
            Control_MouseRightClick((Control)sender, e.Button);
        }

        private void Label_MouseClick(object sender, MouseEventArgs e)
        {
            Control_MouseRightClick((Control)sender, e.Button);
        }

        private void TextBox_MouseClick(object sender, MouseEventArgs e)
        {
            Control_MouseRightClick((Control)sender, e.Button);
        }

        private void CheckBox_MouseClick(object sender, MouseEventArgs e)
        {
            Control_MouseRightClick((Control)sender, e.Button);
        }
        #endregion

        #region 新控件右键菜单
        private void 删除ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Control control = ((ContextMenuStrip)(((ToolStripMenuItem)sender).Owner)).SourceControl;
            control.Parent.Controls.Remove(control);
        }

        private void 编辑ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Control control = ((ContextMenuStrip)(((ToolStripMenuItem)sender).Owner)).SourceControl;

            FmControlAttribute fmControlAttribute = new FmControlAttribute(control);
            //fmControlAttribute.TopLevel = false;
            fmControlAttribute.Text = "属性编辑";
            fmControlAttribute.StartPosition = FormStartPosition.CenterParent;
            fmControlAttribute.setControlAttribute += FmControlAttribute_setControlAttribute;
            if (fmControlAttribute.ShowDialog() == DialogResult.OK)
            {
                control.Name = controlAttributes.Name;
                control.Text = controlAttributes.Text;
                //MessageBox.Show("修改完成！");
            }
            fmControlAttribute.Dispose();
        }

        private void FmControlAttribute_setControlAttribute(Control control)
        {

            foreach (PropertyInfo propertyInfoGet in control.GetType().GetProperties())
            {
                if (AppSets.propertyNames.Contains(propertyInfoGet.Name))
                {
                    var proSet = controlAttributes.GetType().GetProperty(propertyInfoGet.Name);
                    proSet.SetValue(controlAttributes, propertyInfoGet.GetValue(control, null), null);
                }
            }
        }


        #endregion

        #region NewControls KeyDown Events
        private void CheckBox_KeyDown(object sender, KeyEventArgs e)
        {
            NewControls_KeyDown_Delete((Control)sender, e.KeyCode);

        }

        private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            NewControls_KeyDown_Delete((Control)sender, e.KeyCode);
        }

        private void Label_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            NewControls_KeyDown_Delete((Control)sender, e.KeyCode);
        }

        private void ComboBox_KeyDown(object sender, KeyEventArgs e)
        {
            NewControls_KeyDown_Delete((Control)sender, e.KeyCode);
        }

        private void Button_KeyDown(object sender, KeyEventArgs e)
        {
            NewControls_KeyDown_Delete((Control)sender, e.KeyCode);
        }

        private void NewControls_KeyDown_Delete(Control control, Keys keys)
        {
            if (keys == Keys.Delete)
                control.Parent.Controls.Remove(control);
        }
        #endregion

        #region 第一工具栏（新建、打开、保存）
        private void 新建NToolStripButton_Click(object sender, EventArgs e)
        {

        }

        private void 打开OToolStripButton_Click(object sender, EventArgs e)
        {

        }

        private void 保存SToolStripButton_Click(object sender, EventArgs e)
        {

        }

        private void 退出QToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion

        #region 第二工具栏
        private void 无操作toolStripButton_Click(object sender, EventArgs e)
        {
            this.plMain.Cursor = Cursors.Default;
            MouseCursorDefaulted = CtrTypeStyle.None;
        }

        private void 固定文字toolStripButton_Click(object sender, EventArgs e)
        {
            this.plMain.Cursor = Resources.UserControlCursor(CtrTypeStyle.Label);

            MouseCursorDefaulted = CtrTypeStyle.Label;
        }

        private void 单行可编辑文字框toolStripButton_Click(object sender, EventArgs e)
        {
            this.plMain.Cursor = Resources.UserControlCursor(CtrTypeStyle.TextBox);

            MouseCursorDefaulted = CtrTypeStyle.TextBox;
        }

        private void 按钮toolStripButton_Click(object sender, EventArgs e)
        {
            this.plMain.Cursor = Resources.UserControlCursor(CtrTypeStyle.Button);

            MouseCursorDefaulted = CtrTypeStyle.Button;
        }

        private void 单选框toolStripButton_Click(object sender, EventArgs e)
        {
            this.plMain.Cursor = Resources.UserControlCursor(CtrTypeStyle.CheckBox);

            MouseCursorDefaulted = CtrTypeStyle.CheckBox;
        }

        private void 下拉框toolStripButton_Click(object sender, EventArgs e)
        {
            this.plMain.Cursor = Resources.UserControlCursor(CtrTypeStyle.ComboBox);

            MouseCursorDefaulted = CtrTypeStyle.ComboBox;
        }
        #endregion


        private void 工具栏ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.工具栏ToolStripMenuItem.Checked = !this.工具栏ToolStripMenuItem.Checked;
            this.toolStrip工具.Visible = this.工具栏ToolStripMenuItem.Checked;
        }

        private void 控件工具条ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.控件工具条ToolStripMenuItem.Checked = !this.控件工具条ToolStripMenuItem.Checked;
            this.toolStrip控件.Visible = this.控件工具条ToolStripMenuItem.Checked;
        }

    }
}
